#include "ThreadRunner.h"
#include <QProcess>
#include <QDebug>

ThreadRunner::ThreadRunner()
{

}

void ThreadRunner::run()
{
    for(auto prs = prss.begin();prs!=prss.end();prs++){
        auto appPath = prs.value().first;
        auto paramsList = prs.value().second;
        QString r2,r3;
        /* 创建一个 QProcess 对象来启动程序 */
        QProcess *process = new QProcess();
        process->setProgram(appPath);
        process->setArguments(paramsList);
        QDateTime startTime = QDateTime::currentDateTime();

        std::cout << "app:" << appPath.toStdString() << std::endl;
        qDebug() << paramsList;
        connect(process, &QProcess::started, [&r2,&r3,startTime]()
        {
            r2 = startTime.toString("yyyy-MM-dd HH:mm:ss");
            r3 = tr("Finished");
        });

        connect(process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
              [&r2,startTime](int exitCode, QProcess::ExitStatus exitStatus){
            QDateTime endTime = QDateTime::currentDateTime();
            if (exitStatus == QProcess::NormalExit && exitCode == 0) {
                r2 = startTime.toString("yyyy-MM-dd HH:mm:ss");
            } else {
                // r3 = "异常退出";
            }
        });


        connect(process, &QProcess::errorOccurred, [&r3,process](QProcess::ProcessError error) {
            r3 = process->errorString();
            std::cout << "error ID:" << int(error) << std::endl;
        });

        int row = prs.key();
        if(prsDetach[row]){
            process->startDetached();
        }else{
            process->start();
            process->waitForFinished();
            //接受进程捕获到输出的消息
            QByteArray output = process->readAllStandardOutput();
            QString msg = QString::fromLocal8Bit(output);
            std::cout << msg.toStdString() << std::endl;
        }

        emit TaskFinished(prs.key(),r2,r3);
        QThread::sleep(5);
    }




}

void ThreadRunner::AddProcess(int row, QString appPath,bool detach, QStringList paramsList, bool allow)
{
    if(allow){
        prss[row] = {appPath,paramsList};
        prsDetach[row] = detach;
    }
}

void ThreadRunner::clear()
{
    prss.clear();
    prsDetach.clear();
}
